// CartController.java
package com.aaa.vegetablemarketexpress.controller;

import com.aaa.vegetablemarketexpress.entity.Cart;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.CartService;
import com.aaa.vegetablemarketexpress.util.Result;
import com.aaa.vegetablemarketexpress.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @FileName: CartController
 * @Description: 购物车控制层
 * @Author:
 * @CreateTime: 2025/9/18
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

   /**
     * 添加商品到购物车
     *
     * @param request 请求数据，包含商品ID和数量
     * @param session 用户会话
     * @return 添加结果
     */
   @PostMapping("/addToCart")
   public Result addToCart(@RequestBody Map<String, Object> request, HttpSession session) {
       try {
           // 从session中获取用户信息
           User user = (User) session.getAttribute("userInfo");
           if (user == null) {
               return ResultUtil.failed("用户未登录");
           }

           // 从请求数据中获取参数
           Long productId = null;
           BigDecimal quantity = new BigDecimal("1");
           BigDecimal price = BigDecimal.ZERO;

           // 检查必要参数
           if (request.get("productId") == null) {
               return ResultUtil.failed("缺少商品ID参数");
           }

           try {
               productId = Long.valueOf(request.get("productId").toString());
           } catch (NumberFormatException e) {
               return ResultUtil.failed("商品ID格式错误");
           }

           // 获取数量参数（如果存在）
           if (request.get("quantity") != null) {
               try {
                   quantity = new BigDecimal(request.get("quantity").toString());
               } catch (NumberFormatException e) {
                   return ResultUtil.failed("数量参数格式错误");
               }
           }

           // 获取价格参数（如果存在）
           if (request.get("price") != null) {
               try {
                   price = new BigDecimal(request.get("price").toString());
               } catch (NumberFormatException e) {
                   return ResultUtil.failed("价格参数格式错误");
               }
           }

           // 获取用户ID
           Long userId = user.getUserId();

           // 创建购物车对象
           Cart cart = new Cart();
           cart.setUserId(userId);
           cart.setProductId(productId);
           cart.setQuantity(quantity);

           // 计算金额 = 单价 * 数量
           cart.setAmount(price.multiply(quantity));

           cart.setCreateTime(new Date());
           cart.setUpdateTime(new Date());

           // 保存到数据库
           boolean result = cartService.addToCart(cart);
           if (result) {
               return ResultUtil.success("添加购物车成功");
           } else {
               return ResultUtil.failed("添加购物车失败");
           }
       } catch (Exception e) {
           e.printStackTrace();
           return ResultUtil.failed("系统异常：" + e.getMessage());
       }
   }

    /**
     * 查询用户购物车详情
     *
     * @param session 用户会话
     * @return 购物车详情列表
     */
    @GetMapping("/getCartDetails")
    public Result getCartDetails(HttpSession session) {
        try {
            // 从session中获取用户信息
            User user = (User) session.getAttribute("userInfo");
            if (user == null) {
                return ResultUtil.failed("用户未登录");
            }

            // 获取用户ID
            Long userId = user.getUserId();

            // 查询购物车详情
            List<Cart> cartDetails = cartService.getCartDetailsByUserId(userId);

            return ResultUtil.success(cartDetails);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failed("系统异常：" + e.getMessage());
        }
    }

    /**
     * 从购物车中删除商品
     *
     * @param cartId  购物车ID
     * @param session 用户会话
     * @return 删除结果
     */
    @DeleteMapping("/removeFromCart")
    public Result removeFromCart(@RequestParam("cartId") Long cartId, HttpSession session) {
        try {
            // 从session中获取用户信息
            User user = (User) session.getAttribute("userInfo");
            if (user == null) {
                return ResultUtil.failed("用户未登录");
            }

            // 删除购物车记录
            boolean result = cartService.removeById(cartId);
            if (result) {
                return ResultUtil.success("删除成功");
            } else {
                return ResultUtil.failed("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failed("系统异常：" + e.getMessage());
        }
    }
    /**
     * 清空用户购物车（基于用户身份验证）
     *
     * @param session 用户会话
     * @return 删除结果
     */
    @DeleteMapping("/clearCart")
    public Result clearCart(HttpSession session) {
        try {
            // 从session中获取用户信息
            User user = (User) session.getAttribute("userInfo");
            if (user == null) {
                return ResultUtil.failed("用户未登录");
            }

            // 获取用户ID
            Long userId = user.getUserId();

            // 删除该用户的所有购物车记录
            boolean result = cartService.clearCartByUserId(userId);
            if (result) {
                return ResultUtil.success("购物车已清空");
            } else {
                return ResultUtil.failed("清空购物车失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failed("系统异常：" + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     *
     * @param cartId  购物车ID
     * @param quantity 商品数量
     * @param session 用户会话
     * @return 更新结果
     */
    @PostMapping("/updateQuantity")
    public Result updateQuantity(@RequestParam("cartId") Long cartId,
                                 @RequestParam("quantity") BigDecimal quantity,
                                 HttpSession session) {
        try {
            // 从session中获取用户信息
            User user = (User) session.getAttribute("userInfo");
            if (user == null) {
                return ResultUtil.failed("用户未登录");
            }

            // 检查数量参数
            if (quantity == null || quantity.compareTo(BigDecimal.ZERO) <= 0) {
                return ResultUtil.failed("商品数量必须大于0");
            }

            // 更新购物车商品数量
            boolean result = cartService.updateQuantity(cartId, quantity);
            if (result) {
                return ResultUtil.success("更新成功");
            } else {
                return ResultUtil.failed("更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.failed("系统异常：" + e.getMessage());
        }
    }

}
